﻿/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{	var div_str = "";
	var fieldIndex = 0;
	var tableIndex = 0;
	var cellNodeRegex = /^(?:td|th)$/;
	/**
	 * 删除单元格
	 * @param selectionOrCell
	 * @returns null*/
	function deleteCells( selectionOrCell )
	{
		if ( selectionOrCell instanceof CKEDITOR.dom.selection )
		{
			var cellsToDelete = getSelectedCells( selectionOrCell );
		//	selectionOrCell.remove();
			var table = cellsToDelete[ 0 ] && cellsToDelete[ 0 ].getAscendant( 'table' );
			var cellToFocus   = getFocusElementAfterDelCells( cellsToDelete );

			for ( var i = cellsToDelete.length - 1 ; i >= 0 ; i-- )
				//deleteCells( cellsToDelete[ i ].$ );
				$(cellsToDelete[ i ].$).html(div_str);

			/*if ( cellToFocus )
				placeCursorInCell( cellToFocus, true );
			else if ( table )
				table.remove();*/
		}
		else if ( selectionOrCell instanceof CKEDITOR.dom.element )
		{
			var tr = selectionOrCell.getParent();
			if ( tr.getChildCount() == 1 ){
				//tr.remove();
			}
			else
				selectionOrCell.remove();
		}
	}
	/**
	 * 
	*/
	function placeCursorInCell( cell, placeAtEnd )
	{
		var range = new CKEDITOR.dom.range( cell.getDocument() );
		if ( !range[ 'moveToElementEdit' + ( placeAtEnd ? 'End' : 'Start' ) ]( cell ) )
		{
			range.selectNodeContents( cell );
			range.collapse( placeAtEnd ? false : true );
		}
		range.select( true );
	}
	/**
	 * */
	function getFocusElementAfterDelCells( cellsToDelete ) {
		var i = 0,
			last = cellsToDelete.length - 1,
			database = {},
			cell,focusedCell,
			tr;

		while ( ( cell = cellsToDelete[ i++ ] ) )
			CKEDITOR.dom.element.setMarker( database, cell, 'delete_cell', true );

		// 1.first we check left or right side focusable cell row by row;
		i = 0;
		while ( ( cell = cellsToDelete[ i++ ] ) )
		{
			if ( ( focusedCell = cell.getPrevious() ) && !focusedCell.getCustomData( 'delete_cell' )
			  || ( focusedCell = cell.getNext()     ) && !focusedCell.getCustomData( 'delete_cell' ) )
			{
				CKEDITOR.dom.element.clearAllMarkers( database );
				return focusedCell;
			}
		}

		CKEDITOR.dom.element.clearAllMarkers( database );

		// 2. then we check the toppest row (outside the selection area square) focusable cell
		tr = cellsToDelete[ 0 ].getParent();
		if ( ( tr = tr.getPrevious() ) )
			return tr.getLast();

		// 3. last we check the lowerest  row focusable cell
		tr = cellsToDelete[ last ].getParent();
		if ( ( tr = tr.getNext() ) )
			return tr.getChild( 0 );

		return null;
	}

	/**
	 * 获得单元格
	 * @param selection
	 * @returns retval*/
	function getSelectedCells( selection )
	{
		var ranges = selection.getRanges();
		var retval = [];
		var database = {};

		function moveOutOfCellGuard( node )
		{
			// Apply to the first cell only.
			if ( retval.length > 0 )
				return;

			// If we are exiting from the first </td>, then the td should definitely be
			// included.
			if ( node.type == CKEDITOR.NODE_ELEMENT && cellNodeRegex.test( node.getName() )
					&& !node.getCustomData( 'selected_cell' ) )
			{
				CKEDITOR.dom.element.setMarker( database, node, 'selected_cell', true );
				retval.push( node );
			}
		}

		for ( var i = 0 ; i < ranges.length ; i++ )
		{
			var range = ranges[ i ];

			if ( range.collapsed )
			{
				// Walker does not handle collapsed ranges yet - fall back to old API.
				var startNode = range.getCommonAncestor();
				var nearestCell = startNode.getAscendant( 'td', true ) || startNode.getAscendant( 'th', true );
				if ( nearestCell )
					retval.push( nearestCell );
			}
			else
			{
				var walker = new CKEDITOR.dom.walker( range );
				var node;
				walker.guard = moveOutOfCellGuard;

				while ( ( node = walker.next() ) )
				{
					// If may be possible for us to have a range like this:
					// <td>^1</td><td>^2</td>
					// The 2nd td shouldn't be included.
					//
					// So we have to take care to include a td we've entered only when we've
					// walked into its children.

					var parent = node.getAscendant( 'td' ) || node.getAscendant( 'th' );
					if ( parent && !parent.getCustomData( 'selected_cell' ) )
					{
						CKEDITOR.dom.element.setMarker( database, parent, 'selected_cell', true );
						retval.push( parent );
					}
				}
			}
		}

		CKEDITOR.dom.element.clearAllMarkers( database );

		return retval;
	}
	
	
	function removeNullField(){
		if(tableIndex && fieldIndex){
			//var form  = parent.$.fn.module.getFormProp(tableIndex);
			var field = parent.$.fn.module.getFieldProp(tableIndex,fieldIndex);
			if(!field.editProperties.editType){
				parent.$.fn.module.deleteRowProp(tableIndex,fieldIndex);
				if(window.doRefreshCurrentPage) {
					doRefreshCurrentPage();
				}
			}else{
				alert("非空字段不允许删除！");
			}
		}else{
			alert("删除失败，失败原因：未选中占位符或已经删除！");
		}
	}
	/**
	 * 
	 * */
	function move_cell(title){
		if(tableIndex && fieldIndex){
				var form  = parent.$.fn.module.getFormProp(tableIndex);
				var field = parent.$.fn.module.getFieldProp(tableIndex,fieldIndex);
				//var temp = field;
				//var form = parent.$.fn.module.getFormProp(tableIndex);
				var tablesId = titleObj[title];
				var tabRow = tablesId.replace(/[^0-9]/ig, "");
				var tab = $("#"+tablesId).tabs("getTab",title);
				var tbby = tab.panel("body");
				var editorId = tab[0].firstElementChild.name;
				var td_str = "";
				if(form){
					var cols = form.cols;
					for(var i=1;i<cols;i++){
						td_str += "<td style='border-right:1px solid #99BBE8;border-top: 1px solid #99BBE8;'><div></div></td>";
					}
				}
				
				if(tbby) {
					var tb_ifr = tbby.find("iframe");
					if(tb_ifr) {
						var win = tb_ifr[0].contentWindow.window.document;
						if(win){
							var editor_tab = $(win).find("table")[0];
							//var cols = editorId.charAt(editorId.length-1);
							var colArr = editorId.split("_");
							var cols = colArr[colArr.length-1];
							//var module = parent.$.fn.module.getModule();
							//var maxIndex = module.maxIndex;
							//var new_field = $.extend({},field,{"tabRows":tabRow,"tabCols":cols,"index":maxIndex++});
							//var editPro = $.extend({},field.editProperties,{"editType":""});
							//$.extend(field,{"caption":"","key":"","editProperties":editPro,"dataProperties":{},"queryProperties":{}});
							//parent.$.fn.module.setModule($.extend(module,{"maxIndex":maxIndex}));
							var new_field = parent.$.fn.module.getNullField({"tabRows":field.tabRows,"tabCols":field.tabCols});
							form.fieldList.push(new_field);
							div_str = covInputType(new_field,tableIndex);
							field["tabRows"] = tabRow;
							field["tabCols"] = cols;
							var str = covInputType(field,tableIndex);
							$(editor_tab).append("<tr><td style='border-right:1px solid #99BBE8;border-top: 1px solid #99BBE8;'>"+str+"</td>"+td_str+"</tr>");
							return true;
						}
					}
				
			}
		}
		return false;
	}
	CKEDITOR.plugins.add( 'tabledrag',{
		init: function( editor )
		{	
		//	var scriptPath = this.path + "redips-drag-source.js";
			var cssPath = this.path + "style.css";
			CKEDITOR.document.appendStyleSheet(cssPath);
		//	CKEDITOR.scriptLoader.load(scriptPath, function( success ) {});
			editor.on( 'instanceReady', function(evt)
					{
						initTableDrag("drag", evt.editor.window.$);
						/*//editor.document.getBody().on('load', function( evt ) {
								var	rd = REDIPS.drag;
								// initialization
								rd.init("drag", evt.editor.window.$);
								// set hover color
								rd.hover.color_td = '#E7C7B2';
								// set drop option to 'shift'
								rd.drop_option = 'switch';
								// set shift mode to vertical2
								rd.shift_option = 'vertical2';
								// enable animation on shifted elements
								rd.animation_shift = true;
								// set animation loop pause
								rd.animation_pause = 20;
								//点击事件时候获得元素属性
								rd.myhandler_clicked();
								//移动到目标位置时获得目标位置的元素属性
								rd.myhandler_changed();
								rd.myhandler_switched();
						//});*/						 							
					});
			
		//	alert(editor.contextMenu);
				if ( editor.contextMenu)
			{	
				
				editor.contextMenu.addListener( function( element)
						{
						
						/*editor.addCommand( 'send',{
							exec : function(editor)
							{	
								
								if(tableIndex && fieldIndex){
									var field = $.fn.module.getFieldProp(tableIndex,fieldIndex);
									var tab = $("#edit_tabs").tabs("getTab","补充信息2");
									var tbby = tab.panel("body");
									var editorId = tab[0].firstElementChild.name;
									if(tbby) {
										var tb_ifr = tbby.find("iframe");
										if(tb_ifr) {
											var win = tb_ifr[0].contentWindow.window.document;
											//var editor_tab = tb_ifr[0].contentDocument.body.firstElementChild.firstElementChild;
											//var editor_tab = tb_ifr[0].c
											if(win){
												var cols = editorId.charAt(editorId.length-1);
												var editor_tab = $(win).find("table")[0];
												var cols = editorId.charAt(editorId.length-1);
												$.extend(field,{"tabCols":cols});
												$(editor_tab).append("<tr><td>11111</td></tr>");
											}
										}
									
								}
									
								}
							}
							
						});*/
						//动态获取分页tab长度往（单元格发送）下级菜单添加内容
						var form = parent.$.fn.module.getModule().dataSource.formList;
						var formKey="";
						var tabList=[];
						for(var i=0;i<form.length;i++){
							if(form[i].isMaster){
								formKey = form[i].key;
							}
						}
						var tabsList =  parent.$.fn.module.getModule().dataSource.tabsList;
						for(var m=0;m<tabsList.length;m++){
							var tab = tabsList[m].tabList;
							for(var n=0;n<tab.length;n++){
								if(tab[n].form==formKey){
									tabList.push(tab[n]);
								}
							}
						}
						var menu_Obj = {};
						var return_Obj ={};
						for(var i=0;i<tabList.length;i++){ 
							var script_name ="send"+i;
							var title = tabList[i].caption;
							editor.addCommand(script_name,{
								exec:function(editor,data){
								//	alert(data);
								//	$.each(editor.contextMenu,function(k,v){alert(k+" : "+v)});
										var flag = move_cell(data);
										if(flag){
											var selection = editor.getSelection();
											deleteCells( selection );
											if(window.doRefreshCurrentPage) {
												doRefreshCurrentPage();
											}
										}
									}
							});
							
							menu_Obj["sendToNo"+i] = {label:tabList[i].caption,command:script_name,group:'myGroup',order:'1'};
							return_Obj["sendToNo"+i] = CKEDITOR.TRISTATE_OFF;									//onClick:'function(){move_cell(tabList[i].caption)}'
						}
						editor.addMenuGroup( 'myGroup' );
						editor.addMenuItems(
								menu_Obj
							);
						
						//添加移除空占位符方法
						editor.addCommand('removeNullField',{exec:function(editor,data){
								//alert("click remove:");
								removeNullField();
							}
						});
						
						//给div层添加（单元格发送）菜单
						editor.addMenuItems({ 'sendItem':
						{
							label : '单元格移动到',
							group :'div',
							order : 5,
							getItems : function()
							{
								return return_Obj;
							}
						},'removeField':{
							label : '移除占位符',
							group :'div',
							order : 6,
							command:'removeNullField'
						}});
						/*editor.addMenuItem( 'removeField',
								{
									label : '移除占位符',
									group :'div',
									order : 5,
									getItems : function()
									{
										return return_Obj;
									}
								});*/
						if ( !element || element.isReadOnly() )
								return null;
			
							var elementPath = new CKEDITOR.dom.elementPath( element ),
								blockLimit = elementPath.blockLimit;
			
							if ( blockLimit && blockLimit.getAscendant( 'div', true ) )
							{	
								var div_obj = element.getAscendant( 'div', true );
								fieldIndex = div_obj.$.id;
								tableIndex = div_obj.$.tabIndex;
								/*fieldIndex = $(div_obj).attr("id");
								tableIndex =  $(div_obj).attr("tabIndex");*/
								var td_obj = {"tableIndex":tableIndex,"fieldIndex":fieldIndex};
								return {sendItem : CKEDITOR.TRISTATE_OFF,removeField : CKEDITOR.TRISTATE_OFF};
							}
			
							return null;
						});
			}
			
		}
	});
})();